<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Message extends Controller_Initial_Page {
   
    /*
     * If $message_id is set, render inbox with slide down specific message, if not render only titles
     */
    public function action_inbox($page = 1,$message_id = null)
    {       
       $content_view = View::factory('content');      
       $message_template_view = View::factory('message/template'); 
       $search_header_view = View::factory('message/search_header');
       
       $user_model = Auth::instance()->get_user();
       $total_inbox_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
       $total_outbox_items = $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
       $total_bin_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',1)
                                  ->count_all() +
                          $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',1)
                                  ->count_all();     
        
       $item_per_page = 12;
                
       $pagination = Pagination::factory(array('total_items'       => $total_inbox_items,
                                               'items_per_page'    => $item_per_page));
        
       $inbox_view = $this->generate_inbox($page, $item_per_page, $message_id);
       
       $search_header_view->set('placeholder', __('find in inbox'))
                          ->set('type', 'inbox')
                          ->set('content', $inbox_view)
                          ->set('pagination', $pagination);
       
       $message_template_view->set('menu_selected',2)
                             ->set('content',$search_header_view)
                             ->set('total_inbox_items', $total_inbox_items)
                             ->set('total_outbox_items', $total_outbox_items)
                             ->set('total_bin_items', $total_bin_items);        

       $content_view->set('content',$message_template_view);
       
       $this->template->set('body',$content_view); 
       
       
            
            
    }
    
    /*
     *  If set $message_id update read_status, else render all inbox page and return in json format
     */
    public function action_ajax_inbox($page = null,$message_id = null)
    {
        if ($message_id)
        {
            $this->update_date_read($message_id);
        }
        else
        {
            $user_model = Auth::instance()->get_user();
            $total_items = $user_model->inbox
                                      ->where('deleted','=',0)
                                      ->where('folder','=',0)
                                      ->count_all();

            $item_per_page = 12;

            $pagination = Pagination::factory(array('total_items'    => $total_items,
                                                    'items_per_page' => $item_per_page));
            
           
            $inbox_view = $this->generate_inbox($page, $item_per_page); 
            
            if (isset($_POST['internal_pagination']) AND $_POST['internal_pagination'] == 1)
            {
              $content = array('success'    => true,
                               'content'    => $inbox_view->render(),
                               'pagination' => $pagination->render()); 
            }
            else
            {    
                $search_header_view = View::factory('message/search_header');
                $search_header_view->set('placeholder', __('find in inbox'))
                                   ->set('type', 'inbox')
                                   ->set('content', $inbox_view->render())
                                   ->set('pagination', $pagination);
                
                $content = array('success'    => true,
                                 'content' =>  $search_header_view->render());                
            }
            
            $this->response->body(json_encode($content)); 
        }
      
              
    }
    
    private function generate_inbox($page = null, $limit = null, $message_id = null, $word = null)
    {
        $user_model = Auth::instance()->get_user();
        $inboxes = ORM::factory('inbox')->get_inbox($user_model->id, $limit, $page, $word);        
        
        $message_inbox_view = View::factory('message/inbox');
        $message_inbox_view->set('inboxes',$inboxes);
        
        // if 'message_id' slide up message, and if id message is unread , updated read status
        if ($message_id)
        {
            $message_inbox_view->set('message_id',$message_id);
            $this->update_date_read($message_id);            
        }
        

        return $message_inbox_view;
    }
    
    public function action_write()
    {
       $user_model = Auth::instance()->get_user();
       $total_inbox_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
       $total_outbox_items = $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
       $total_bin_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',1)
                                  ->count_all() +
                          $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',1)
                                  ->count_all();    
        
       $content_view = View::factory('content');      
       $message_template_view = View::factory('message/template');    
       
       
       $message_template_view->set('menu_selected',1)
                             ->set('content',$this->generate_write()->render())
                             ->set('total_inbox_items', $total_inbox_items)
                             ->set('total_outbox_items', $total_outbox_items)
                             ->set('total_bin_items', $total_bin_items);       
       $content_view->set('content',$message_template_view);
       
       $this->template->set('body',$content_view);      
    }
    
    public function action_ajax_write()
    {
        if ($_POST)
        {
            
        }
        else
        {
            $content = array('content'=>$this->generate_write()->render());
            $this->response->body(json_encode($content));
        }
    }
    
    private function generate_write()
    {
        $message_write_view = View::factory('message/write');
        return $message_write_view;
    }
    
    public function action_outbox($page = 1, $message_id = null)
    {
       $content_view = View::factory('content');      
       $message_template_view = View::factory('message/template'); 
       $search_header_view = View::factory('message/search_header');
       
       $user_model = Auth::instance()->get_user();
       $total_inbox_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
       $total_outbox_items = $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
       $total_bin_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',1)
                                  ->count_all() +
                          $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',1)
                                  ->count_all();   
        
       $item_per_page = 12;
                
       $pagination = Pagination::factory(array('total_items'       => $total_outbox_items,
                                               'items_per_page'    => $item_per_page));
        
       $outbox_view = $this->generate_outbox($page, $item_per_page, $message_id);
       
       $search_header_view->set('placeholder', __('find in outbox'))
                          ->set('type', 'outbox')
                          ->set('content', $outbox_view)
                          ->set('pagination', $pagination);

       $message_template_view->set('content', $search_header_view)
                             ->set('menu_selected',3)
                             ->set('total_inbox_items', $total_inbox_items)
                             ->set('total_outbox_items', $total_outbox_items)
                             ->set('total_bin_items', $total_bin_items); 
       
       $content_view->set('content',$message_template_view);
       
       $this->template->set('body',$content_view);
    }
    
    public function action_ajax_outbox($page = 1, $message_id = null)
    {
        $user_model = Auth::instance()->get_user();
        $total_items = $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
        
        $item_per_page = 12;
                
        $pagination = Pagination::factory(array('total_items'       => $total_items,
                                                'items_per_page'    => $item_per_page));
        
        $outbox_view = $this->generate_outbox($page, $item_per_page); 
        
        if (isset($_POST['internal_pagination']) AND $_POST['internal_pagination'] == 1)
        {
            $content = array('success'    => true,
                             'content'    => $outbox_view->render(),
                             'pagination' => $pagination->render());               
        }
        else
        { 
            
            $search_header_view = View::factory('message/search_header');
            $search_header_view->set('placeholder', __('find in outbox'))
                               ->set('type', 'outbox')
                               ->set('content', $outbox_view->render())
                               ->set('pagination', $pagination);

            $content = array('success'    => true,
                             'content' =>  $search_header_view->render());   
        }

        $this->response->body(json_encode($content));        
    }
    
    private function generate_outbox($page = null, $limit = null, $message_id = null, $word = null)
    {
        $user_model = Auth::instance()->get_user();
        $outboxes = ORM::factory('outbox')->get_outbox($user_model->id, $limit, $page, $word);

        
        $message_outbox_view = View::factory('message/outbox');
        $message_outbox_view->set('outboxes',$outboxes);
        
        if ($message_id)
        {
            $message_outbox_view->set('message_id',$message_id);
        }
        return $message_outbox_view;      
    }
    
    public function action_bin($page = 1, $message_id = null)
    {
        $content_view = View::factory('content');      
        $message_template_view = View::factory('message/template'); 
        $search_header_view = View::factory('message/search_header');

        $user_model = Auth::instance()->get_user();
        
        $total_inbox_items = $user_model->inbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
       
        $total_outbox_items = $user_model->outbox
                                  ->where('deleted','=',0)
                                  ->where('folder','=',0)
                                  ->count_all();
        
        $message_model = ORM::factory('message');
        $total_bin_items = $message_model->join('outboxes')->on('messages.id','=','outboxes.message_id')
                                  ->join('inboxes')->on('messages.id','=','inboxes.message_id')
                                  ->where_open()
                                  ->where('outboxes.user_id', '=', $user_model->id)
                                  ->where('outboxes.folder', '=', 1)
                                  ->where('outboxes.deleted', '=', 0)
                                  ->where_close()
                                  ->or_where_open()
                                  ->where('inboxes.user_id', '=', $user_model->id)
                                  ->where('inboxes.folder', '=', 1)
                                  ->where('inboxes.deleted', '=', 0)
                                  ->or_where_close()
                                  ->distinct('message')
                                  ->count_all();

        $item_per_page = 12;

        $pagination = Pagination::factory(array('total_items'       => $total_bin_items,
                                                'items_per_page'    => $item_per_page));


        $bin_view = $this->generate_bin($page, $item_per_page, $message_id);

        $search_header_view->set('placeholder', __('find in bin'))
                           ->set('type', 'bin')
                           ->set('content', $bin_view)
                           ->set('pagination', $pagination);

        $message_template_view->set('content', $search_header_view)
                              ->set('menu_selected',4)
                              ->set('total_inbox_items', $total_inbox_items)
                              ->set('total_outbox_items', $total_outbox_items)
                              ->set('total_bin_items', $total_bin_items); 
        $content_view->set('content',$message_template_view);

        $this->template->set('body',$content_view);

    }
    
    public function action_ajax_bin($page = 1, $message_id = null)
    {
        $user_model = Auth::instance()->get_user();
        
        $message_model = ORM::factory('message');
        $total_items = $message_model->join('outboxes')->on('messages.id','=','outboxes.message_id')
                                  ->join('inboxes')->on('messages.id','=','inboxes.message_id')
                                  ->where_open()
                                  ->where('outboxes.user_id', '=', $user_model->id)
                                  ->where('outboxes.folder', '=', 1)
                                  ->where('outboxes.deleted', '=', 0)
                                  ->where_close()
                                  ->or_where_open()
                                  ->where('inboxes.user_id', '=', $user_model->id)
                                  ->where('inboxes.folder', '=', 1)
                                  ->where('inboxes.deleted', '=', 0)
                                  ->or_where_close()
                                  ->distinct('message')
                                  ->count_all();
     
        $item_per_page = 12;
                
        $pagination = Pagination::factory(array('total_items'       => $total_items,
                                                'items_per_page'    => $item_per_page));
        
        $bin_view = $this->generate_bin($page , $item_per_page);
        
        if (isset($_POST['internal_pagination']) AND $_POST['internal_pagination'] == 1)
        {
            $content = array('success'    => true,
                             'content'    => $bin_view->render(),
                             'pagination' => $pagination->render());                    
        }
        else
        {
            $search_header_view = View::factory('message/search_header');
            $search_header_view->set('placeholder', __('find in bin'))
                               ->set('type', 'bin')
                               ->set('content', $bin_view->render())
                               ->set('pagination', $pagination);

            $content = array('success'    => true,
                             'content' =>  $search_header_view->render());        
        }

        $this->response->body(json_encode($content)); 
    }
    
    private function generate_bin($page = null, $limit = null, $message_id = null, $word = null)
    {
       
        $user_model = Auth::instance()->get_user();
        
        $messages = ORM::factory('message')->get_bin($user_model->id, $limit, $page, $word);
        
        $message_bin_view = View::factory('message/bin');
        $message_bin_view->set('messages', $messages);
        $message_bin_view->set('my_id', $user_model->id);
        
        if ($message_id)
        {
            $message_bin_view->set('message_id',$message_id);
        }
        
        return $message_bin_view;           
    }
    
    public function action_ajax_delete_inbox_message($id)
    {
         $auth_model = Auth::instance()->get_user();
         $inbox_model = $auth_model->inbox->where('id','=',$id)->find();
        
        if ($inbox_model->folder == 1)
        {
            $inbox_model->deleted = 1;
        }
        else
        {
            $inbox_model->folder = 1;
        }

        
        $inbox_model->update();
    }
    
    public function action_ajax_delete_outbox_message($id)
    {
        $auth_model = Auth::instance()->get_user();
        $outbox_model = $auth_model->outbox->where('id','=',$id)->find();
        
        if ($outbox_model->folder == 1)
        {
            $outbox_model->deleted = 1;
        }
        else
        {
            $outbox_model->folder = 1;
        }
        
        $outbox_model->update();
         
    }
    
    public function action_ajax_send_message()
    {
        if ($_POST)
        {
            $my_user_model = Auth::instance()->get_user();
            
            $outbox_model = ORM::factory('outbox');
            $message_model = ORM::factory('message');
            
            $message_model->values($_POST, array('subject','content_message'));
                        
            $external_values = array('recipient' => (array_key_exists('recipient',$_POST) AND !empty($_POST['recipient'])));
            $extra_rules = Validation::factory($external_values)
                           ->rule('recipient', 'not_empty')
                           ->labels(array('recipient' => __('Recipient')));
                        
            //TODO: check permission to which user i can send message [optimal solution!!!]
            
            try
            { 
                $message_id = $message_model->save($extra_rules); //save message 
                
                // prepare email message  
                $email_title_message = Kohana::message('email', 'send_message.title');
                $email_title_message = __($email_title_message, array(
                            ':name' => $my_user_model->user_profile->name.' '.$my_user_model->user_profile->surname
                        ));
                $main_config = Kohana::config('main');  
                
                $email_template_view = View::factory('email/template');
                $email_content_view = View::factory('email/send_message');
                $email_content_view->set('message_subject',Security::xss_clean($_POST['subject']));
                $email_content_view->set('message_content',Security::xss_clean($_POST['content_message']));
                $email_template_view->set('title', $email_title_message);
                $email_template_view->set('content', $email_content_view);
                
               
                $recipients = explode(',',$_POST['recipient']);
                
                foreach($recipients as $user_id)
                {
                    $user_model = ORM::factory('user', $user_id);
                    
                    $inbox_model = ORM::factory('inbox');
                    $inbox_model->user_id = $user_id;
                    $inbox_model->message_id = $message_id;
                    $inbox_model->save();
                    
                    // SEND E-MAIL TO USER IF WANT TO
                    if($user_model->user_privacy->new_message_notification)
                    {
                         $send_email = Email::factory($email_title_message)
                                            ->message($email_template_view, 'text/html')
                                            ->to($user_model->email)
                                            ->from($main_config->contact_mail, $main_config->contact_name)
                                            ->send();
                         
                         if(!$send_email)
                         {
                              Log::instance()->add(Log::ERROR, 'Information about new message in inbox could not be sent to '.$user_model->email);
                         }
                    }
                    
                }
               
                
                
                $outbox_model->user_id = $my_user_model->id;
                $outbox_model->message_id = $message_id;
                $outbox_model->save();
                
                $output = array('success' => 'true',
                                'message' => 'Yes Yes Yes');
            }
            catch (ORM_Validation_Exception $e)
            {
                 $output = array('success' => 'false', 
                                 'message' => 'Oh no!', 
                                 'errors'  => $e->errors('validation'));
            }
            
            $this->response->body(json_encode($output));
                        
        }
    }
    

    
    private function update_date_read($id)
    {
        //TODO: check if this resource is my resource but maybe ORM relation will solve this problem
         $auth_model = Auth::instance()->get_user();
         $inbox_model = $auth_model->inbox->where('id','=',$id)->find();
        
        if($inbox_model->date_read == null)
        {        
            $inbox_model->date_read = DB::expr('NOW()');
            $inbox_model->update();
        }
    }
    
    public function action_ajax_get_toggle()
    {
        $user_model = Auth::instance()->get_user();
        $messages = ORM::factory('inbox')->get_inbox($user_model->id, 5);
        
        //update user notice table
        foreach($messages as $message)
        {
            $notice_model = $user_model->notice;
            $notice_model->inbox_id = $message->id;
            $notice_model->save();
            break;
        }
        
        $message_toggle_template_view = View::factory('message/toggle_template');
        $message_toggle_template_view->set('messages',$messages);
        
        $content = array('content' => $message_toggle_template_view->render());
        $this->response->body(json_encode($content));
    }
    
    public function action_ajax_search($type, $page)
    {
        $user_model = Auth::instance()->get_user();
        $item_per_page = 12;
        
        switch ($type)
        {
            case 'inbox':
                
                 $total_items = $user_model->inbox
                                           ->join('messages')->on('messages.id','=','inboxes.message_id')
                                           ->where('deleted','=',0)
                                           ->where('folder','=',0)
                                           ->where_open()
                                                ->where('messages.subject', 'LIKE', '%'.$_GET['search'].'%')
                                                ->or_where('messages.content_message', 'LIKE', '%'.$_GET['search'].'%')
                                           ->where_close()
                                           ->count_all();
                
                
                $pagination = Pagination::factory(array('total_items'       => $total_items,
                                                        'items_per_page'    => $item_per_page));
                
                $inbox_view = $this->generate_inbox($page, $item_per_page, null, $_GET['search']);
                $content = array('success'    => true,
                                 'content'    => $inbox_view->render(),
                                 'pagination' => $pagination->render());
                break;
            
            case 'outbox':
                
                $total_items = $user_model->outbox
                                          ->join('messages')->on('messages.id','=','outboxes.message_id')
                                          ->where('deleted','=',0)
                                          ->where('folder','=',0)
                                          ->where_open()
                                              ->where('messages.subject', 'LIKE', '%'.$_GET['search'].'%')
                                              ->or_where('messages.content_message', 'LIKE', '%'.$_GET['search'].'%')
                                          ->where_close()
                                          ->count_all();
                
                $pagination = Pagination::factory(array('total_items'       => $total_items,
                                                        'items_per_page'    => $item_per_page));
                
                $outbox_view = $this->generate_outbox($page, $item_per_page, null, $_GET['search']);
                $content = array('success'    => true,
                                 'content'    => $outbox_view->render(),
                                 'pagination' => $pagination->render());
                break;
            
            case 'bin':
                
                $message_model = ORM::factory('message');
                $total_items = $message_model->join('outboxes')->on('messages.id','=','outboxes.message_id')
                                             ->join('inboxes')->on('messages.id','=','inboxes.message_id')
                                             ->where_open()
                                                  ->where('outboxes.user_id', '=', $user_model->id)
                                                  ->where('outboxes.folder', '=', 1)
                                                  ->where('outboxes.deleted', '=', 0)
                                             ->where_close()
                                             ->or_where_open()
                                                  ->where('inboxes.user_id', '=', $user_model->id)
                                                  ->where('inboxes.folder', '=', 1)
                                                  ->where('inboxes.deleted', '=', 0)
                                             ->or_where_close()
                                             ->where_open()
                                                 ->where('messages.subject', 'LIKE', '%'.$_GET['search'].'%')
                                                 ->or_where('messages.content_message', 'LIKE', '%'.$_GET['search'].'%')
                                             ->where_close()
                                             ->distinct('message')
                                             ->count_all();
                
                $pagination = Pagination::factory(array('total_items'       => $total_items,
                                                        'items_per_page'    => $item_per_page));
                
                $bin_view = $this->generate_bin($page, $item_per_page, null, $_GET['search']);
                $content = array('success'    => true,
                                 'content'    => $bin_view->render(),
                                 'pagination' => $pagination->render());
                break;
            default:
                throw new HTTP_Exception_404;
        }
        
         $this->response->body(json_encode($content));
    }
}